package com.leoman.controller.api;

import com.leoman.core.ErrorType;
import com.leoman.core.bean.Result;
import com.leoman.entity.AppUser;
import com.leoman.entity.Banner;
import com.leoman.entity.CompanyUser;
import com.leoman.entity.Province;
import com.leoman.exception.*;
import com.leoman.service.AppUserService;
import com.leoman.service.BannerService;
import com.leoman.service.ProvinceService;
import com.leoman.utils.JsonUtil;
import com.leoman.utils.WebUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 基本api
 * Created by 涂奕恒 on 2016/10/18 0018.
 */
@Controller
@RequestMapping(value = "api/index")
public class IndexApi {

    @Autowired
    private AppUserService appUserService;

    @Autowired
    private BannerService bannerService;

    @Autowired
    private ProvinceService provinceService;

    /**
     * @api {post} /api/index/sendCode 1、发送验证码
     * @apiVersion 0.0.1
     * @apiName index.sendCode
     * @apiGroup index
     *
     * @apiDescription 发送验证码
     *
     * @apiParam {String}   mobile      手机号                                                    (必填)
     * @apiParam {Integer}  type        验证码类型，1=注册，2=忘记密码，3=绑定手机号，默认为1          (必填)
     * @apiParam {Integer}  isCompany   用户类型，0=普通用户，1=企业用户，不填默认为0
     *
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *      "status":0,
     *      "msg":"",
     *      "data":{
     *          "code": 236541
     *      }
     * }
     */
    @RequestMapping(value = "/sendCode")
    public void sendCode(HttpServletResponse response, String mobile, Integer type, Integer isCompany) {
        try {
            String code = appUserService.sendCode(mobile, type, isCompany);
            String result = JsonUtil.obj2ApiJson(Result.successInfoApi(code, "code"));
            WebUtil.printApi(response, result);
        } catch (ParamErrorException e) {
            WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_NOT_PARAM));
        } catch (MobileExistException e) {
            WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_MOBILE_EXIST));
        } catch (MobileNotFindException e) {
            WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_MOBILE_NOT_FIND));
        }
    }

    /**
     * @api {post} /api/index/checkCodeStatus 2、检测验证码是否正确
     * @apiVersion 0.0.1
     * @apiName index.checkCodeStatus
     * @apiGroup index
     *
     * @apiDescription 检测验证码是否正确
     *
     * @apiParam {String}  mobile      手机号                                        (必填)
     * @apiParam {String}  code        验证码                                        (必填)
     * @apiParam {Integer} type        验证码类型，1=注册，2=忘记密码，3=绑定手机号，默认为1
     * @apiParam {Integer} isCompany   用户类型，0=普通用户，1=企业用户，不填默认为0
     *
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *      "status": 0,
     *      "msg": "",
     *      "data": {}
     * }
     */
    @RequestMapping(value = "/checkCodeStatus")
    public void checkCodeStatus(HttpServletResponse response, String mobile, String code, Integer type, Integer isCompany) {
        if (StringUtils.isBlank(mobile) || StringUtils.isBlank(code)) {
            WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_NOT_PARAM));
            return;
        }

        // 1=验证码不正确 2=验证码类型不正确 3=验证码超时
        Integer flag = appUserService.checkCode(mobile, code, type, isCompany);
        switch (flag){
            case 0:
                WebUtil.printApi(response, Result.successApi());
                break;
            case 1:
                WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_CODE_ERROR));
                break;
            case 2:
                WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_CODE_TYPE_ERROR));
                break;
            case 3:
                WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_CODE_OUT_TIME));
                break;
            case 4:
                WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_USER_TYPE_ERROR));
                break;
            default:
                WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_BASE));
                break;
        }
    }

    /**
     * @api {post} /api/index/register 3、注册
     * @apiVersion 0.0.1
     * @apiName index.register
     * @apiGroup index
     *
     * @apiDescription 注册
     *
     * @apiParam {String}   mobile                      手机号         (必填)
     * @apiParam {String}   password                    密码           (必填)
     * @apiParam {String}   code                        验证码         (必填)
     * @apiParam {Integer}  isCompany                   用户类型，0=普通用户，1=企业用户，不填默认为0
     *
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *      "status": 0,
     *      "msg": "",
     *      "data": {}
     * }
     */
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public void register(HttpServletResponse response, String mobile, String password, String code, Integer isCompany) {
        try {
            appUserService.iRegister(mobile, password, code, isCompany);
            String result = JsonUtil.obj2ApiJson(Result.successApi());
            WebUtil.printApi(response, result);
        } catch (ParamErrorException e) {
            WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_NOT_PARAM));
        } catch (MobileExistException e) {
            WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_MOBILE_EXIST));
        } catch (CodeErrorException e) {
            WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_CODE_ERROR));
        }
    }

    /**
     * @api {post} /api/index/login 4、登录
     * @apiVersion 0.0.1
     * @apiName index.login
     * @apiGroup index
     *
     * @apiDescription 登录
     *
     * @apiParam   {String}   mobile                    手机号         (必填)
     * @apiParam   {String}   password                  密码           (必填)
     *
     * @apiSuccess {Object}   userInfo
     * @apiSuccess {Integer}  userInfo.id               id
     * @apiSuccess {String}   userInfo.nickName         昵称
     * @apiSuccess {String}   userInfo.avatar           头像
     * @apiSuccess {String}   userInfo.mobile           手机
     * @apiSuccess {Integer}  userInfo.sex              性别
     * @apiSuccess {Integer}  userInfo.age              年龄
     * @apiSuccess {Integer}  userInfo.regionId         所在区域ID
     * @apiSuccess {String}   userInfo.email            电子邮箱
     * @apiSuccess {Integer}  userInfo.money            账户余额
     * @apiSuccess {String}   userInfo.aliPayName       支付宝用户名
     * @apiSuccess {String}   userInfo.aliPayAccount    支付宝账号
     * @apiSuccess {String}   userInfo.createTime       注册时间
     * @apiSuccess {String}   userInfo.updateTime       修改时间
     *
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *      "status": 0,
     *      "msg": "",
     *      "data": {
     *          "userInfo": {
     *              "id": 14,
     *              "nickName": "老大",
     *              "avatar": "",
     *              "mobile": "13872116519",
     *              "sex": 0,
     *              "age": 0,
     *              "regionId": "",
     *              "email": "",
     *              "money": 0,
     *              "aliPayName": "",
     *              "aliPayAccount": "",
     *              "createTime": "1474600084564",
     *              "updateTime": "1474600084564"
     *          }
     *      }
     * }
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public void login(HttpServletResponse response, String mobile, String password) {
        try {
            AppUser appUser = appUserService.iAppUserLogin(mobile, password);
            String result = JsonUtil.obj2ApiJson(Result.successInfoApi(appUser, "userInfo"), "password", "type", "region", "openId");
            WebUtil.printApi(response, result);
        } catch (ParamErrorException e) {
            WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_NOT_PARAM));
        } catch (MobileNotFindException e) {
            WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_MOBILE_NOT_FIND));
        } catch (PasswordErrorException e) {
            WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_PASSWORD_ERROR));
        } catch (UserSealStatusException e) {
            WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_USER_STATUS_DISABLED));
        }
    }

    /**
     * @api {post} /api/index/loginPlus 5、第三方登录
     * @apiVersion 0.0.1
     * @apiName index.loginPlus
     * @apiGroup index
     *
     * @apiDescription 第三方登录
     *
     * @apiParam {String}     openId                    唯一标识                                (必填)
     * @apiParam {Integer}    type                      类型，1=QQ，2=微信，3=微博               (必填)
     * @apiParam {String}     avatar                    头像
     * @apiParam {String}     nickName                  昵称
     *
     * @apiSuccess {Object}   userInfo
     * @apiSuccess {Integer}  userInfo.id               id
     * @apiSuccess {String}   userInfo.nickName         昵称
     * @apiSuccess {String}   userInfo.avatar           头像
     * @apiSuccess {String}   userInfo.mobile           手机
     * @apiSuccess {Integer}  userInfo.sex              性别
     * @apiSuccess {Integer}  userInfo.age              年龄
     * @apiSuccess {Integer}  userInfo.regionId         所在区域ID
     * @apiSuccess {String}   userInfo.email            电子邮箱
     * @apiSuccess {Integer}  userInfo.money            账户余额
     * @apiSuccess {String}   userInfo.aliPayName       支付宝用户名
     * @apiSuccess {String}   userInfo.aliPayAccount    支付宝账号
     * @apiSuccess {String}   userInfo.createTime       注册时间
     * @apiSuccess {String}   userInfo.updateTime       修改时间
     *
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *      "status": 0,
     *      "msg": "",
     *      "data": {
     *          "userInfo": {
     *              "id": 14,
     *              "nickName": "老大",
     *              "avatar": "",
     *              "mobile": "13872116519",
     *              "sex": 0,
     *              "age": 0,
     *              "regionId": "",
     *              "email": "",
     *              "money": 0,
     *              "aliPayName": "",
     *              "aliPayAccount": "",
     *              "createTime": "1474600084564",
     *              "updateTime": "1474600084564"
     *          }
     *      }
     * }
     */
    @RequestMapping(value = "/loginPlus", method = RequestMethod.POST)
    public void loginPlus(HttpServletResponse response, String openId, Integer type, String avatar, String nickName) {
        try {
            AppUser appUser = appUserService.iLoginPlus(openId, type, avatar, nickName);
            String result = JsonUtil.obj2ApiJson(Result.successInfoApi(appUser, "userInfo"), "password", "type", "region", "openId");
            WebUtil.printApi(response, result);
        } catch (ParamErrorException e) {
            WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_NOT_PARAM));
        } catch (ThirdTypeErrorException e) {
            WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_THIRD_TYPE_ERROR));
        } catch (UserSealStatusException e) {
            WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_USER_STATUS_DISABLED));
        }
    }

    /**
     * @api {post} /api/index/companyLogin 6、企业用户登录
     * @apiVersion 0.0.1
     * @apiName index.companyLogin
     * @apiGroup index
     *
     * @apiDescription 登录
     *
     * @apiParam   {String}   mobile                           手机号         (必填)
     * @apiParam   {String}   password                         密码           (必填)
     *
     * @apiSuccess {Object}   companyUserInfo
     * @apiSuccess {Integer}  companyUserInfo.id               id
     * @apiSuccess {String}   companyUserInfo.nickName         昵称
     * @apiSuccess {Integer}  companyUserInfo.type             类型，0=未申请认证，1=个人认证，2=企业认证
     * @apiSuccess {String}   companyUserInfo.mobile           联系方式
     * @apiSuccess {Integer}  companyUserInfo.checkStatus      审核状态，0=待审核，1=审核通过，2=审核失败
     * @apiSuccess {String}   companyUserInfo.checkFailReason  审核失败原因
     * @apiSuccess {Integer}  companyUserInfo.money            账户余额
     * @apiSuccess {Integer}  companyUserInfo.staticMoney      冻结金额
     * @apiSuccess {String}   companyUserInfo.createTime       注册时间
     * @apiSuccess {String}   companyUserInfo.updateTime       修改时间
     *
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *      "status": 0,
     *      "msg": "",
     *      "data": {
     *          "companyUserInfo": {
     *              "id": 14,
     *              "nickName": "老大",
     *              "type": 0,
     *              "mobile": "13872116519",
     *              "checkStatus": 0,
     *              "checkFailReason": "",
     *              "money": 2000,
     *              "staticMoney": 1000,
     *              "createTime": "1474600084564",
     *              "updateTime": "1474600084564"
     *          }
     *      }
     * }
     */
    @RequestMapping(value = "/companyLogin", method = RequestMethod.POST)
    public void companyLogin(HttpServletResponse response, String mobile, String password) {
        try {
            CompanyUser companyUser = appUserService.iCompanyUserLogin(mobile, password);
            String result = JsonUtil.obj2ApiJson(Result.successInfoApi(companyUser, "companyUserInfo"), "password", "sendTime", "sealStatus");
            WebUtil.printApi(response, result);
        } catch (ParamErrorException e) {
            WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_NOT_PARAM));
        } catch (MobileNotFindException e) {
            WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_MOBILE_NOT_FIND));
        } catch (PasswordErrorException e) {
            WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_PASSWORD_ERROR));
        } catch (UserSealStatusException e) {
            WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_USER_STATUS_DISABLED));
        }
    }

    /**
     * @api {post} /api/index/forgetPwd 7、忘记密码
     * @apiVersion 0.0.1
     * @apiName index.forgetPwd
     * @apiGroup index
     *
     * @apiDescription 忘记密码
     *
     * @apiParam {String}   mobile                    手机号              (必填)
     * @apiParam {String}   password                  密码                (必填)
     * @apiParam {String}   code                      验证码              (必填)
     * @apiParam {Integer}  isCompany                 用户类型，0=普通用户，1=企业用户，不填默认为0
     *
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *      "status": 0,
     *      "msg": "",
     *      "data": {}
     * }
     */
    @RequestMapping(value = "/forgetPwd", method = RequestMethod.POST)
    public void forgetPwd(HttpServletResponse response, String mobile, String password, String code, Integer isCompany) {
        try {
            appUserService.iForgetPwd(mobile, password, code, isCompany);
            String result = JsonUtil.obj2ApiJson(Result.successApi());
            WebUtil.printApi(response, result);
        } catch (ParamErrorException e) {
            WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_NOT_PARAM));
        } catch (MobileNotFindException e) {
            WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_MOBILE_NOT_FIND));
        } catch (CodeErrorException e) {
            WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_CODE_ERROR));
        } catch (UserSealStatusException e) {
            WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_USER_STATUS_DISABLED));
        }
    }

    /**
     * @api {post} /api/index/bindingMobile 8、绑定手机号
     * @apiVersion 0.0.1
     * @apiName index.bindingMobile
     * @apiGroup index
     *
     * @apiDescription 绑定手机号
     *
     * @apiParam {Integer}  userId                    用户ID              (必填)
     * @apiParam {String}   mobile                    手机号              (必填)
     * @apiParam {String}   password                  密码                (必填)
     * @apiParam {String}   code                      验证码              (必填)
     * @apiParam {Integer}  isCompany                 用户类型，0=普通用户，1=企业用户，不填默认为0
     *
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *      "status": 0,
     *      "msg": "",
     *      "data": {}
     * }
     */
    @RequestMapping(value = "/bindingMobile", method = RequestMethod.POST)
    public void bindingMobile(HttpServletResponse response, Integer userId, String mobile, String password, String code, Integer isCompany) {
        try {
            appUserService.iBindingMobile(userId, mobile, password, code, isCompany);
            WebUtil.printApi(response, JsonUtil.obj2ApiJson(Result.successApi()));
        } catch (ParamErrorException e) {
            WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_NOT_PARAM));
        } catch (UserNotFindException e) {
            WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_USER_NOT_FIND));
        } catch (MobileExistException e) {
            WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_MOBILE_EXIST));
        } catch (CodeErrorException e) {
            WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_CODE_ERROR));
        } catch (UserSealStatusException e) {
            WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_USER_STATUS_DISABLED));
        }
    }

    /**
     * @api {post} /api/index/listBanner 9、首页banner图列表
     * @apiVersion 0.0.1
     * @apiName index.listBanner
     * @apiGroup index
     *
     * @apiDescription 首页banner图列表
     *
     * @apiSuccess {Object}   list
     * @apiSuccess {Integer}  list.id               banner图ID
     * @apiSuccess {String}   list.cover            封面地址
     * @apiSuccess {String}   list.linkUrl          外链地址(为空:则跳转视频详情)
     * @apiSuccess {Integer}  list.typeId           视频分类id
     * @apiSuccess {Integer}  list.videoId          视频ID
     * @apiSuccess {String}   list.createTime       创建时间
     * @apiSuccess {String}   list.updateTime       修改时间
     *
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *      "status":0,
     *      "msg":"",
     *      "data":{
     *          "list": [
     *              {
     *                  "id" : 1,
     *                  "cover" : "http://4.16.3.22:8080/images/cover.jpg",
     *                  "linkUrl" : "http://4.16.3.22:8080/slsp/doc/index.html",
     *                  "typeId" : "",
     *                  "videoId" : "",
     *                  "createTime" : "1476843473471",
     *                  "updateTime" : "1476843673494"
     *              }
     *          ]
     *      }
     * }
     */
    @RequestMapping(value = "/listBanner", method = RequestMethod.POST)
    public void listBanner(HttpServletResponse response) {
        List<Banner> list = bannerService.iFindList();
        String result = JsonUtil.obj2ApiJson(Result.successListApi(list));
        WebUtil.printApi(response, result);
    }

    /**
     * @api {post} /api/index/addFeedBack 10、添加意见反馈
     * @apiVersion 0.0.1
     * @apiName index.addFeedBack
     * @apiGroup index
     *
     * @apiDescription 添加意见反馈
     *
     * @apiParam {Integer}  userId                    用户ID              (必填)
     * @apiParam {String}   mobile                    手机号
     * @apiParam {String}   content                   反馈内容            (必填)
     * @apiParam {Integer}  isCompany                 用户类型，0=普通用户，1=企业用户，不填默认为0
     *
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *      "status": 0,
     *      "msg": "",
     *      "data": {}
     * }
     */
    @RequestMapping(value = "/addFeedBack", method = RequestMethod.POST)
    public void addFeedBack(HttpServletResponse response, Integer userId, String mobile, String content, Integer isCompany) {
        try {
            if (StringUtils.isBlank(content)) {
                WebUtil.printApi(response, JsonUtil.obj2ApiJson(Result.failureApi(ErrorType.ERROR_NOT_PARAM)));
                return;
            }
            appUserService.iAddFeedBack(userId, mobile, content, isCompany);
            WebUtil.printApi(response, JsonUtil.obj2ApiJson(Result.successApi()));
        } catch (ParamErrorException e) {
            WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_NOT_PARAM));
        } catch (UserNotFindException e) {
            WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_USER_NOT_FIND));
        } catch (MobileNotFindException e) {
            WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_MOBILE_NOT_FIND));
        } catch (UserSealStatusException e) {
            WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_USER_STATUS_DISABLED));
        }
    }

    /**
     * @api {post} /api/index/listProvince 11、省市区列表
     * @apiVersion 0.0.1
     * @apiName index.listProvince
     * @apiGroup index
     *
     * @apiDescription 省市区列表
     *
     * @apiSuccess {Object}   list                                省份列表
     * @apiSuccess {Integer}  list.id                             省份id
     * @apiSuccess {String}   list.name                           省份名称
     * @apiSuccess {Object}   list.cityList                       城市列表
     * @apiSuccess {Integer}  list.cityList.id                    城市id
     * @apiSuccess {String}   list.cityList.name                  城市名称
     * @apiSuccess {Object}   list.cityList.regionList            区域列表
     * @apiSuccess {Integer}  list.cityList.regionList.id         区域id
     * @apiSuccess {String}   list.cityList.regionList.name       区域名称
     *
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *      "status":0,
     *      "msg":"",
     *      "data":{
     *          "list": [
     *              {
     *                  "id" : 1,
     *                  "name" : "北京",
     *                  "cityList" : [
     *                      {
     *                          "id" : 1,
     *                          "name" : "北京市",
     *                          "regionList" : [
     *                              {
     *                                  "id" : 1,
     *                                  "name" : "东城区"
     *                              },
     *                              {
     *                                  "id" : 2,
     *                                  "name" : "西城区"
     *                              }
     *                          ]
     *                      }
     *                  ]
     *              }
     *          ]
     *      }
     * }
     */
    @RequestMapping(value = "/listProvince", method = RequestMethod.POST)
    public void listProvince(HttpServletResponse response) {
        List<Province> list = provinceService.findList();
        String result = JsonUtil.obj2ApiJson(Result.successListApi(list), "province", "city", "region");
        WebUtil.printApi(response, result);
    }
}
